"use strict";
import path = require('path');
var cors = require('cors');
import express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var utils = require('./modules/utils')
import { config } from './modules/config';
var DailyFile = require('./modules/common/dailyfile');
var dynamicRoute = require('./modules/common/dynamic-routes');
var debug = require('debug')('menpuji-ldc:server');
import https = require('https');
var lodash = require('lodash');

var app = express();

app.use(cors({
    origin: "*",
    methods: 'GET,POST,PUT,DELETE,OPTIONS'
}));

app.use(logger('common', {
    stream: DailyFile.getStream({
        filename: path.normalize(path.join(config.logRootDir, 'access-%DATE%.log')),
        date_format: 'YYYYMMDDHH',
        frequency: '1h',
        verbose: false
    })
}));
if (process.env.NODE_ENV != 'test') app.use(logger('dev'));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }));
app.use(cookieParser());

dynamicRoute.loads(app, __dirname + '/routes', '../../routes/');


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    (<any>err).status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use([function (err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: err
        });
    }]);
}

// production error handler
// no stacktraces leaked to user
app.use([function (err, req, res, next) {
    res.status(err.status || 500);
    res.json(<any>'error', {
        message: err.message,
        error: {}
    });
}]);


var port = 8876;
app.set('port', port);
var faye = require('faye');
var fs = require("fs");
let dir = "/extracted/fbs/certificate/";
if (process.env.NODE_ENV == "development") dir = "/certificate/";

var options = {
    key: fs.readFileSync(path.normalize(process.cwd() + dir + 'ca.key')),
    cert: fs.readFileSync(path.normalize(process.cwd() + dir + 'ca.crt'))
};
var server = https.createServer(options, app);
var bayeux = new faye.NodeAdapter({ mount: '/faye', timeout: 45 });
bayeux.attach(server);
server.listen(port, "0.0.0.0");
server.on('error', (error) => {
    if (error.syscall !== 'listen') {
        throw error;
    }
    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;
    switch (error.code) {
        case 'EACCES':
            logger.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            logger.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
});
server.on('listening', () => {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
});
//# sourceMappingURL=rest-httpsServer.js.map